/**
 * Intercept the deserialized response here, and log it to the memory logger.
 * 
 */
package common.unit;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializationConfig;
import common.logging.Item;

/**
 * @author zrawji
 * 
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ManipulateMessageBodyReader extends JacksonJsonProvider implements MessageBodyReader<Object>
{

    private final ObjectMapper mapper = new ObjectMapper();
    final ObjectWriter ow;
    boolean printDebugRealTime;
    // This is a bit of a hack. We want to ensure our log entities are grouped together. Since we
    // are not able to capture the
    // status code here cleanly, we use the same logResponseItems list and populate it higher up on
    // the http stack with the
    // status code. *Sometimes* we can get two status codes populated before we hit the reader, that
    // is why we also add the
    // uri that the status code is in reference to...to help with debugging.
    final ArrayList<Item> logResponseItems;

    /**
     * @param logResponseItems
     * 
     */
    public ManipulateMessageBodyReader(ArrayList<Item> logResponseItems)
    {
        super();
        String isDebug = System.getProperty("printDebug");
        printDebugRealTime = Boolean.parseBoolean(isDebug);

        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false).configure(
            SerializationConfig.Feature.INDENT_OUTPUT, true);
        ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        this.logResponseItems = logResponseItems;
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType,
                    Annotation[] annotations, MediaType mediaType)
    {
        return super.isReadable(type, genericType, annotations, mediaType);
    }

    @Override
    public Object readFrom(Class<Object> type, Type genericType,
                    Annotation[] annotations, MediaType mediaType,
                    MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
                    throws IOException, WebApplicationException
    {
        Object myObject = super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);

        if (httpHeaders.size() > 0)
        {
            for (Entry<String, List<String>> e : httpHeaders.entrySet())
            {
                for (String v : e.getValue())
                {
                    logResponseItems.add(new Item(e.getKey(), v));
                }
            }
        }
        logResponseItems.add(new Item("response_payload", ow.writeValueAsString(myObject)));
        Item[] array = new Item[logResponseItems.size()];
        array = logResponseItems.toArray(array);
        logResponseItems.clear();

        return myObject;
    }

}
